<template>
  <div>
    <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片部分 -->
    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置参数！！！"
        type="warning"
        show-icon
      >
      </el-alert>
      <!-- 选择商品 -->
      <p>
        选择商品的分类：
        <!-- v-modul中是与props中value双向绑定 -->
        <el-cascader
          v-model="cascaderKey"
          :options="cateList"
          :props="cascaderprops"
          @change="handleChange"
          clearable
        ></el-cascader>
      </p>
      <!-- tab展示部分 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="静态属性" name="first">
          <el-button type="primary" @click="isaddonly" :disabled="isbea">
            添加属性
          </el-button>
          <el-table :data="paramsonlyList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(scope.row, val)"
                  :key="index"
                  v-for="(val, index) in scope.row.attr_vals"
                  :disable-transitions="false"
                >
                  {{ val }}
                </el-tag>
                <el-input
                  class="taginput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagRef"
                  size="mini"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" align="center" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="editparams(scope.row)"
                  size="mini"
                  icon="el-icon-edit"
                >
                  编辑
                </el-button>
                <el-button
                  @click="deleteparams(scope.row.attr_id)"
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="动态参数" name="second">
          <el-button type="primary" @click="isaddmany" :disabled="isbea">
            添加参数
          </el-button>
          <el-table :data="paramsmanyList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  @close="handleClose(scope.row, val)"
                  :key="index"
                  v-for="(val, index) in scope.row.attr_vals"
                  :disable-transitions="false"
                >
                  {{ val }}
                </el-tag>
                <el-input
                  class="taginput"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagRef"
                  size="mini"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >
                  + New Tag
                </el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"> </el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  @click="editparams(scope.row)"
                  size="mini"
                  icon="el-icon-edit"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  @click="deleteparams(scope.row.attr_id)"
                  size="mini"
                  icon="el-icon-delete"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加弹出框 -->
    <el-dialog
      @close="addDialogClose"
      :title="this.text + '添加'"
      :visible.sync="isPopup"
      width="50%"
    >
      <el-form
        ref="addParamsRef"
        :rules="addParamsFromRules"
        :model="addParamsForm"
        label-width="80px"
      >
        <el-form-item :label="this.text + '名称'" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isPopup = false">取 消</el-button>
        <el-button type="primary" @click="okAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog
      @close="editDialogClose"
      :title="this.text + '修改'"
      :visible.sync="isedit"
      width="50%"
    >
      <el-form
        ref="editParamsRef"
        :rules="editParamsFromRules"
        :model="editParamsForm"
        label-width="80px"
      >
        <el-form-item :label="this.text + '名称'" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isedit = false">取 消</el-button>
        <el-button type="primary" @click="okedit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Params',
  created() {
    this.getCateList()

  },
  data() {
    return {
      // 商品分类列表
      cateList: [],
      // 参数列表
      paramsonlyList: [],
      // 属性列表
      paramsmanyList: [],
      //联机选择器配置
      cascaderprops: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: "hover",

      },
      //将联级选择器双向绑定获得的id定义成一个数组
      cascaderKey: [],
      //   tab双向绑定默认为first
      activeName: 'first',
      // 添加表单中的数据
      addParamsForm: { attr_name: '' },
      editParamsForm: { attr_name: '' },
      //商品属性的id
      paramsId: 0,
      // 是否弹出添加框
      isPopup: false,
      // 是否弹修改框 
      isedit: false,

      // 表单规则
      addParamsFromRules: {
        attr_name: [{ required: true, message: `请输入内容`, trigger: 'blur' }]
      },
      editParamsFromRules: {
        attr_name: [{ required: true, message: `请输入内容`, trigger: 'blur' }]
      }


    }
  },
  methods: {
    //获取商品分类列表
    getCateList() {
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/categories`)
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.cateList = response.data.data;
          }
        }).catch((error) => console.log(error))
    },
    // 获取参数列表
    getParamslist() {
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes`,
        { params: { sel: this.isParams } })
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            response.data.data.forEach(item => {
              item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : []
              // 动态属性标签输入框是否显示
              item.inputVisible = false
              // 动态属性标签输入框双向绑定
              item.inputValue = ''
            });

            if (this.isParams === 'only') {
              this.paramsonlyList = response.data.data;
            } else {
              this.paramsmanyList = response.data.data;

            }

          }
        }).catch((error) => console.log(error))
    },
    //   联机选择器数据变化后调用  
    handleChange() {
      if (this.cascaderKey.length !== 3) {
        this.cascaderKey = []
        this.paramsonlyList = []
        this.paramsmanyList = []
        return
      }
      this.getParamslist()
    },
    // 监视tab中的数据变化
    handleTabClick() {
      this.getParamslist()
    },
    // 是否弹出添加静态属性的框
    isaddonly() {
      this.isPopup = true
    },
    isaddmany() {
      this.isPopup = true
    },
    // 确定添加
    okAdd() {
      this.$refs.addParamsRef.validate(valid => {
        if (valid) {
          this.$http.post(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes`,
            {
              attr_name: this.addParamsForm.attr_name,
              attr_sel: this.isParams
            })
            .then((response) => {
              if (response.data.meta.status !== 201) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success(response.data.meta.msg);
                this.getParamslist()
                this.isPopup = false
              }
            }).catch((error) => console.log(error))
        } else {
          this.$message.error('请输入完整的信息!!!');
        }

      })
    },
    // 重置表单
    addDialogClose() {
      this.$refs.addParamsRef.resetFields()
    },
    editDialogClose() {
      this.$refs.editParamsRef.resetFields()
    },
    // 修改参数
    editparams(info) {
      this.paramsId = info.attr_id
      this.$http.get(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes/${info.attr_id}`,
        { attr_sel: this.isParams })
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.editParamsForm.attr_name = response.data.data.attr_name
            this.isedit = true
          }
        }).catch((error) => console.log(error))

    },
    //确定修改
    okedit() {
      this.$refs.editParamsRef.validate(valid => {
        if (valid) {
          this.$http.put(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes/${this.paramsId}`,
            {
              attr_name: this.editParamsForm.attr_name,
              attr_sel: this.isParams
            })
            .then((response) => {
              if (response.data.meta.status !== 200) {
                this.$message.error(response.data.meta.msg);
              } else {
                this.$message.success(response.data.meta.msg);
                this.getParamslist()
                this.isedit = false
              }
            }).catch((error) => console.log(error))
        } else {
          this.$message.error('请输入完整的信息!!!');
        }

      })

    },
    // 删除参数
    deleteparams(id) {
      this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.delete(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes/${id}`)
          .then((response) => {
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              this.$message.success(response.data.meta.msg);
              this.getParamslist()
            }
          }).catch((error) => console.log(error))

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除动态属性
    handleClose(val, text) {
      val.attr_vals.splice(val.attr_vals.indexOf(text), 1);
      this.$http.put(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes/${val.attr_id}`,
        {
          attr_name: val.attr_name,
          attr_sel: val.attr_sel,
          attr_vals: val.attr_vals.join(" ")
        })
        .then((response) => {
          if (response.data.meta.status !== 200) {
            this.$message.error(response.data.meta.msg);
          } else {
            this.$message.success(response.data.meta.msg);
          }
        }).catch((error) => console.log(error))

    },
    // 展示动态属性输入框
    showInput(val) {
      val.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagRef.$refs.input.focus();
      });
    },
    // 变回按钮
    handleInputConfirm(val) {
      let inputValue = val.inputValue;
      if (inputValue.trim().length !== 0) {
        val.attr_vals.push(inputValue);
        val.inputVisible = false;
        val.inputValue = '';
        console.log(val);
        this.$http.put(`http://127.0.0.1:8888/api/private/v1/categories/${this.cascaderKeyId}/attributes/${val.attr_id}`,
          {
            attr_name: val.attr_name,
            attr_sel: val.attr_sel,
            attr_vals: val.attr_vals.join(" ")
          })
          .then((response) => {
            if (response.data.meta.status !== 200) {
              this.$message.error(response.data.meta.msg);
            } else {
              this.$message.success(response.data.meta.msg);
            }
          }).catch((error) => console.log(error))
      }
      val.inputVisible = false;
      val.inputValue = '';
    }

  },
  computed: {
    // 按钮是否禁用
    isbea() {
      if (this.cascaderKey.length !== 3) {
        return true
      } else {
        return false
      }
    },
    // 传入的参数id
    cascaderKeyId() {
      if (this.cascaderKey.length === 3) {
        return this.cascaderKey[2]
      }
      return 0
    },
    // 不同的页面传入不同的参数
    isParams() {
      if (this.activeName === 'first') {
        return 'only'
      } else {
        return 'many'
      }
    },
    // 不同的页面出现不同的文字
    text() {
      if (this.activeName === 'first') {
        return '属性'
      } else {
        return '参数'
      }

    },






  }

}
</script>

<style scoped>
.el-table {
  margin-top: 20px;
}
.taginput {
  width: 100px;
}
.button-new-tag,
.el-tag {
  margin: 10px;
}
</style>